package com.seventh.parkingrent.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.seventh.parkingrent.common.Encrypt;
import com.seventh.parkingrent.common.Result;
import com.seventh.parkingrent.controller.form.LoginForm;
import com.seventh.parkingrent.controller.form.PasswordForm;
import com.seventh.parkingrent.controller.form.UserForm;
import com.seventh.parkingrent.dao.UserMapper;
import com.seventh.parkingrent.domain.User;
import com.seventh.parkingrent.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Length;
import org.springframework.context.annotation.Configuration;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.util.List;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author Lucas
 * @since 2021-08-24
 */
@RestController
@Slf4j
@CrossOrigin("*")
public class UserController {

    @Resource
    private IUserService userService;



    @PostMapping("/login")
    public Result login(@RequestBody @Valid LoginForm loginForm, BindingResult bindingResult) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        log.info("进入登录方法{}", loginForm);
        if (bindingResult.hasErrors()) {
            List<FieldError> allErrors = bindingResult.getFieldErrors();
            StringBuilder strBuilder = new StringBuilder();
            for (FieldError error : allErrors) {
                strBuilder.append(error.getField() + ":" + error.getDefaultMessage() + ";");
            }
            return Result.fail("ARGUEMTN_ERROR", strBuilder.toString());
        } else {
            String username = loginForm.getUsername();
            if (username.length() == 0) {
                return Result.fail("ARGUEMTN_ERROR", "用户名不能为空");
            }
        }
        String s = Encrypt.md5(loginForm.getPassword());
        User user = userService.login(loginForm.getUsername(), s);
        if (null != user&&user.getState().equals("1")) {
            return Result.success(user);
        }
        return Result.fail("该用户未激活");
    }

    @GetMapping("getlessor")
    public Result getLessorById(Integer id) {
        log.info("获得出租人信息,获得id：{}", id);
        User user = userService.getUserById(id);
        return Result.success(user);
    }

    @GetMapping("/findEmail")
    public Result findEmail(String email) {
        log.info("进入查询邮箱{}", email);

        if (null == email || "".equals(email)) {
            return Result.fail("邮箱不能为空");
        }
        User user = userService.findEmail(email);
        return user == null ? Result.success("邮箱可以使用") : Result.fail("该邮箱已被注册");
    }

    @PostMapping("/register")
    public Result register(@RequestBody @Valid UserForm userForm, BindingResult bindingResult) throws Exception {
        log.info("进入注册方法{}", userForm);
        if (bindingResult.hasErrors()) {
            List<FieldError> allErrors = bindingResult.getFieldErrors();
            StringBuilder strBuilder = new StringBuilder();
            for (FieldError error : allErrors) {
                strBuilder.append(error.getField() + ":" + error.getDefaultMessage() + ";");
            }
            return Result.fail("ARGUEMTN_ERROR", strBuilder.toString());
        } else {
            String username = userForm.getUsername();
            String email = userForm.getEmail();
            String phone = userForm.getPhone();
            String idcard = userForm.getIdcard();
            if (username.length() == 0) {
                return Result.fail("ARGUEMTN_ERROR", "用户名不能为空");
            }
            if (email.length() == 0) {
                return Result.fail("ARGUEMTN_ERROR", "邮箱不能为空");
            }
            if (phone.length() == 0) {
                return Result.fail("ARGUEMTN_ERROR", "手机号不能为空");
            }
            if (idcard.length() == 0) {
                return Result.fail("ARGUEMTN_ERROR", "身份证不能为空");
            }
        }
        boolean b = userService.registerUser(userForm);
        if (b) {
            return Result.success("注册成功");
        }
        return Result.fail("注册失败");
    }

    //邮箱点击激活
    @GetMapping("/updateState")
    public Result updateState(String email) {
        log.info("进入修改邮箱激活接口");
        boolean b = userService.updateState(email);
        if (b) {
            return Result.success("激活成功");
        }
        return Result.fail("激活失败");
    }

    //查询身份证
    @GetMapping("/findIdcard")
    public Result findIdcard(String idcard) {
        log.info("进入查询身份证号接口{}", idcard);
        if (null == idcard || "".equals(idcard)) {
            return Result.fail("身份证号不能为空");
        } else {
            User user = userService.findIdcard(idcard);

            return null == user ? Result.success("该身份证号可以使用") : Result.fail("该身份证号已被占用");
        }
    }


    @PostMapping("/updatePassword")
    public Result updatePassword(@RequestBody @Valid PasswordForm passwordForm, BindingResult bindingResult) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        log.info("进入修改密码接口{}", passwordForm);
        if (bindingResult.hasErrors()) {
            List<FieldError> allErrors = bindingResult.getFieldErrors();
            StringBuilder strBuilder = new StringBuilder();
            for (FieldError error : allErrors) {
                strBuilder.append(error.getField() + ":" + error.getDefaultMessage() + ";");
            }
            return Result.fail("ARGUEMTN_ERROR", strBuilder.toString());
        }
        boolean b = userService.updatePassword(passwordForm);
        return b ? Result.success("修改成功") : Result.fail("修改失败");
    }

    @GetMapping("/findBalance")
    public Result  findBalance(int userId){
        log.info("进入返回用户userId{}",userId);
        User user = userService.findBalance(userId);
        return Result.success(user);
    }
}